package com.lagou.controller;

import com.lagou.pojo.Article;
import com.lagou.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName ArticleController
 * @Description TODO
 * @Author Administrator
 * Date 2020/3/22 0022 下午 1:47
 * Version 1.0
 */
@Controller
public class ArticleController {

    private int pageSize = 2;

    @Autowired
    private ArticleService articleService;

    @RequestMapping("/")
    public String index(Model model, HttpServletRequest request){
        Page<Article> allPageable = null;
        String toPageAction = request.getParameter("toPageAction");
        if (!StringUtils.isEmpty(toPageAction)) {
            String toPage = request.getParameter("toPage");
            int toPageInt = Integer.parseInt(toPage);
            String totalPages = request.getParameter("totalPages");
            int totalPagesInt = Integer.parseInt(totalPages);
            // 上一页
            if ("prev".equals(toPageAction) && toPageInt  >=0) {
                allPageable = articleService.findAllPageable(toPageInt, pageSize);
            }else if ("prev".equals(toPageAction) && toPageInt < 0){
                allPageable = articleService.findAllPageable(0, pageSize);
            } else if ("next".equals(toPageAction) && toPageInt > totalPagesInt-1) { //下一页
                allPageable = articleService.findAllPageable(totalPagesInt-1, pageSize);
            } else if ("next".equals(toPageAction) && toPageInt <= totalPagesInt){
                allPageable = articleService.findAllPageable(toPageInt, pageSize);
            }
        }else{
            allPageable = articleService.findAllPageable(0, pageSize);
        }
        List<Article> articles = allPageable.getContent();
        model.addAttribute("articles", articles);
        model.addAttribute("currentPage",allPageable.getPageable().getPageNumber());
        model.addAttribute("totalPages",allPageable.getTotalPages());
        System.out.println("查询结果为:" + articles + ";currentPage:" + allPageable.getPageable().getPageNumber() + ";totalPages:" + allPageable.getTotalPages());
        return "index";
    }
}
